package SpringBoot.spring_boot_starter_security.D03_权限校验.service;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.titan.core.utils.object.VariantFive;

/**
 *
 *
 * @author 周成功
 *
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        VariantFive<String,String,String,String,String> user = null;
        if("admin".equals(userName)) {
            user = VariantFive.$(userName, "123456", "管理员", "", "");
        } else if("user".equals(userName)) {
            user = VariantFive.$(userName, "123", "业务员", "", "");
        } else {
            throw new UsernameNotFoundException("UserName " + userName + " not found");
        }

        SecurityUser seu = new SecurityUser(user);
        return seu;
    }

    
    class SecurityUser implements UserDetails {
        private static final long serialVersionUID = 1L;
        private VariantFive<String,String,String,String,String> user = null;
        
        SecurityUser(VariantFive<String,String,String,String,String> user) {
        }
        
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            
            if("admin".equals(user.getV1())) {
                authorities.add( new SimpleGrantedAuthority("ADMIN") );
                authorities.add( new SimpleGrantedAuthority("USER") );
            } else if("user".equals(user.getV1())) {
                authorities.add( new SimpleGrantedAuthority("USER") );
            } else {
                throw new UsernameNotFoundException("UserName " + user.getV1() + " not found");
            }
            return authorities;
        }
        
        @Override
        public String getPassword() {
            return user.getV2();
        }
        
        @Override
        public String getUsername() {
            return user.getV3();
        }
        
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
        
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
        
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
        
        @Override
        public boolean isEnabled() {
            return true;
        }
    }
}
